package com.hyg.lib_common.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.testting.DepressedData;
import com.hyg.lib_common.DataModel.testting.InsomniaData;
import com.hyg.lib_common.DataModel.testting.StressData;
import com.hyg.lib_common.DataModel.testting.TesttingAnswer;
import com.hyg.lib_common.DataModel.testting.TesttingXinliQuestion;
import com.hyg.lib_common.R;
import com.hyg.lib_common.databinding.ActivityTestSelfJingshenBinding;
import com.hyg.lib_common.listener.RCVchlickListener;
import com.hyg.lib_common.ui.adpter.RadioButtonAnswerAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class TestSelfJingshenActivity extends BaseActivity {

    ArrayList<TesttingXinliQuestion> list;
    int currentIndex = 0;
    ImageView BackIv;
    TextView titleTv, totalNumber, totalMin, progressTv, questionTv;
    RecyclerView answerRCV;
    Button BackOffBtn, NextBtn, FinishBtn;
    ActivityTestSelfJingshenBinding binding;
    RadioButtonAnswerAdapter adapter;
    public boolean isChooseFlag = false;

    String type = "1";
    String DataBaseDir = "testtingquestions";
    String questionData = "";
    Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTestSelfJingshenBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 60, null, null, true);
        init();
    }

    public void init() {
        initdata();
        initView();
    }

    public void initdata() {
        list = new ArrayList<>();
        type = getIntent().getStringExtra("type");
        getQuestionList(type);
    }

    public void initView() {
        binding.lnTitleView.tvTitle.setText(type);
        binding.lnTitleView.tvTitleMore.setText("问卷介绍");
        binding.lnTitleView.tvTitleMore.setVisibility(View.VISIBLE);
        binding.lnTitleView.tvTitleMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TestSelfJingshenActivity.this, TesttingSelfIntroActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
            }
        });
        binding.lnTitleView.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.btnBackOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updataView(--currentIndex);
            }
        });
        binding.btnNextQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChecked()) {
                    updataView(++currentIndex);
                } else {
                    Toast.makeText(TestSelfJingshenActivity.this, "您尚未选择答案！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        binding.btnFinishQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TestSelfJingshenActivity.this, TestSelfResultActivity.class);
                intent.putExtra("type", type);
                intent.putExtra("result", parseResult(type));
                startActivity(intent);
                finish();
            }
        });
        initRecycleView();
        updataView(currentIndex);
    }


    public void updataView(int position) {
        if (list == null) return;
        binding.tvQuestionNumber.setText(list.size() + "");
        binding.tvQuestionTime.setText((list.size() / 6 + 1) + "");
        binding.tvQuestionIndex.setText((position + 1) + "/" + list.size());
        binding.tvQuestion.setText(list.get(position).getQuestion());
        if (position == 0) {
            binding.btnBackOff.setVisibility(View.GONE);
        } else {
            binding.btnBackOff.setVisibility(View.VISIBLE);
        }
        if (position == list.size() - 1) {
            binding.btnFinishQuestion.setVisibility(View.VISIBLE);
            binding.btnNextQuestion.setVisibility(View.GONE);
        } else {
            binding.btnFinishQuestion.setVisibility(View.GONE);
            binding.btnNextQuestion.setVisibility(View.VISIBLE);
        }
        adapter = new RadioButtonAnswerAdapter(this, list.get(currentIndex).getArrayList(), new RCVchlickListener() {
            @Override
            public void onItemClickListener() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (currentIndex < list.size() - 1) {
                            updataView(++currentIndex);
                        }
                    }
                }, 400);

            }
        });
        binding.rcvQuestion.setAdapter(adapter);
    }

    public void initRecycleView() {
        if (list == null) return;
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        adapter = new RadioButtonAnswerAdapter(this, list.get(currentIndex).getArrayList(), new RCVchlickListener() {
            @Override
            public void onItemClickListener() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (currentIndex < list.size() - 1) {
                            updataView(++currentIndex);
                        }
                    }
                }, 400);
            }
        });
        binding.rcvQuestion.setLayoutManager(layoutManager);
        binding.rcvQuestion.setAdapter(adapter);
    }

    public boolean isChecked() {
        for (TesttingAnswer answer : list.get(currentIndex).getArrayList()) {
            if (answer.isChoose())
                return true;
        }
        return false;
    }


    public void getQuestionList(String type) {
        String name = "";
        String questionData = "";
        switch (type) {
            case "抑郁辨识":
                name = "DepressedData_1.0.0.json";
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 5);
                break;
            case "焦虑辨识":
                name = "AnxiousData_1.0.0.json";
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 5);
                break;
            case "失眠检测":
                name = "InsomniaData_1.0.0.json";
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 4);
                break;
            case "心里压力测试":
                name = "StressData_1.0.0.json";
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 2);
                break;
            case "疲劳辨识":
                name = "FatigueData_1.0.0.json";
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 5);
                break;
        }


    }

    public String getQuestionData(String path) {
        questionData = "";
        try {
            AssetManager manager = getResources().getAssets();
            InputStream inputStream = manager.open(DataBaseDir + "/" + path);
            InputStreamReader isr = null;
            isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String length;
            while ((length = br.readLine()) != null) {
                sb.append(length + "\n");
            }
            br.close();
            isr.close();
            inputStream.close();
            questionData = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return questionData;
    }

    public ArrayList<TesttingXinliQuestion> parseQuestionList(String data, int mark) {
        Log.i("lgb", "parseQuestionList  data===: " + data);
        ArrayList<TesttingXinliQuestion> list = new ArrayList<>();
        switch (mark) {
            case 2:
                ArrayList<StressData> list_StressData = (ArrayList<StressData>) JSONArray.parseArray(data, StressData.class);
                for (StressData stressData : list_StressData) {
                    list.add(new TesttingXinliQuestion(stressData.getQuestions(), stressData.getOption0(), stressData.getOption1()));
                }
                break;
            case 4:
                ArrayList<InsomniaData> list_InsomniaDatad = (ArrayList<InsomniaData>) JSONArray.parseArray(data, InsomniaData.class);
                for (InsomniaData insomniaData : list_InsomniaDatad) {
                    list.add(new TesttingXinliQuestion(insomniaData.getQuestions(), insomniaData.getOption0(), insomniaData.getOption1(), insomniaData.getOption2(), insomniaData.getOption3()));
                }
                break;
            case 5:
                ArrayList<DepressedData> list_Depressed = (ArrayList<DepressedData>) JSONArray.parseArray(data, DepressedData.class);
                for (DepressedData depressedData : list_Depressed) {
                    list.add(new TesttingXinliQuestion(depressedData.getQuestions(), depressedData.getOption0(), depressedData.getOption1(), depressedData.getOption2(), depressedData.getOption3(), depressedData.getOption4()));
                }
                break;
        }
        return list;
    }


    public String parseResult(String type) {
        String result = "";
        switch (type) {
            case "抑郁辨识":
                result = getYiyuResult(calculateScoreTogether(list));
                break;
            case "焦虑辨识":
                result = getJiaolvResult(calculateScoreTogether(list));
                break;
            case "失眠检测":
                result = getShimianResult(calculateScoreTogether(list));
                break;
            case "心里压力测试":
                result = getYaliResult(calculateScoreTogether(list));
                break;
            case "疲劳辨识":
                result = getYiyuResult(calculateScoreTogether(list));
                break;
        }
        return result;
    }


    public int calculateScoreSingle(ArrayList<TesttingAnswer> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChoose()) {
                sum = i;
                return sum;
            }
        }
        return sum;
    }

    public int calculateScoreTogether(ArrayList<TesttingXinliQuestion> list) {
        int sum = 0;
        for (TesttingXinliQuestion question : list) {
            sum += calculateScoreSingle(question.getArrayList());
        }
        return sum;
    }


    public String getYiyuResult(int score) {
        String result = "健康";
        if (score <= 52) {
            result = "健康";
        } else if (score <= 62) {
            result = "轻度抑郁";
        } else if (score <= 72) {
            result = "中度抑郁";
        } else {
            result = "重度抑郁";
        }
        return result;
    }

    public String getJiaolvResult(int score) {
        String result = "健康";
        if (score <= 49) {
            result = "健康";
        } else if (score <= 59) {
            result = "轻度焦虑";
        } else if (score <= 69) {
            result = "中度焦虑";
        } else {
            result = "重度焦虑";
        }
        return result;
    }


    public String getYaliResult(int score) {
        String result = "健康";
        if (score <= 5) {
            result = "健康";
        } else if (score <= 10) {
            result = "正常压力范围";
        } else if (score <= 15) {
            result = "压力较大";
        } else {
            result = "压力过大";
        }
        return result;
    }


    public String getShimianResult(int score) {
        String result = "健康";
        if (score <= 4) {
            result = "健康";
        } else if (score <= 6) {
            result = "可疑失眠";
        } else if (score <= 15) {
            result = "失眠";
        }
        return result;
    }

    @Override
    public void finish() {
        super.finish();
        handler.removeCallbacksAndMessages(null);
    }
}